package com.bing.services.impl;

import com.bing.bean.exception.BingException;
import com.bing.entity.CStatus;
import com.bing.services.EnvService;
import com.bing.utils.UtilFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by kaibb on 15-12-26.
 */

@Component
public class EnvServiceImpl implements EnvService, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(EnvService.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

    @Value("${env.editorDir:editor}")
    private String editorDir;

    @Value("${env.editorUrl:/images/editor/}")
    private String editorUrl;

    @Value("${env.view.pageSize:9}")
    private int pageSize;

    @Value("${env.view.hotSize:12}")
    private int hotSize;

    @Value("${env.tag.size:4}")
    private int tagSize;

    @Override
    public synchronized String copyAndGetEditorFileUrl(MultipartFile multipartFile) {
        try {
            String today = sdf.format(new Date());
            String resourceLocation = editorDir + File.separator + today;
            File file = new File(resourceLocation);
            if (!file.exists()) {
                LOGGER.info("创建目录: {}", file.getAbsolutePath());
                file.mkdirs();
                file.setWritable(true);
            }
            resourceLocation = resourceLocation + File.separator + multipartFile.getSize() + "_" + multipartFile.getOriginalFilename();
            String urlLocation = today + "/" + multipartFile.getSize() + "_" + multipartFile.getOriginalFilename();
            FileCopyUtils.copy(multipartFile.getBytes(), ResourceUtils.getFile(resourceLocation));
            LOGGER.info("上传文件成功:{}", resourceLocation);
            return editorUrl + urlLocation;
        } catch (FileNotFoundException e) {
            throw new BingException("");
        } catch (IOException e) {
            throw new BingException("");
        }
    }

    @Override
    public CStatus[] getCStatus() {
        return CStatus.values();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        UtilFactory.createDir(editorDir);
    }

    @Override
    public int getPageSize() {
        return pageSize;
    }

    @Override
    public int getHotSize() {
        return hotSize;
    }

    @Override
    public int getInt(String name) {
        switch (name) {
            case "tagSize":
                return tagSize;
        }
        return 0;
    }
}
